﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace CCFlow
{
    /// <summary>
    /// Handler 的摘要说明
    /// 这个是为了做一个简单的子系统的演示需要与后台数据库交互.
    /// </summary>
    public class Handler : IHttpHandler
    {
        string dsn = null;
        public HttpContext context = null;
        public void ProcessRequest(HttpContext cont)
        {
            //获得数据库连接地址.
            // this.dsn = System.Configuration.ConfigurationManager.AppSettings["AppCenterDSN"];
            this.dsn = "Password=123;Persist Security Info=True;User ID=ccbpmdemo;Initial Catalog=DevelopERPDemo;Data Source=140.143.236.168;Timeout=999;MultipleActiveResultSets=true";
            //设置通用的变量.
            context = cont;

            //获取执行标记.
            string doType = context.Request.QueryString["DoType"];
            if (doType == null || doType.Equals(""))
                doType = context.Request.QueryString["DoWhat"];

            string sql = null;
            DataTable dt = null;
            string json = null;

            switch (doType)
            {
                case "Portal_Login_Submit": //请求登录.
                    Portal_Login_Submit();
                    return;
                case "AppDemo_CustomerList_Init": //获得客户列表.
                    sql = "SELECT * FROM CRM_Customer ";
                    dt = this.RunSQLReturnDataTable(sql);
                    json = Newtonsoft.Json.JsonConvert.SerializeObject(dt, Newtonsoft.Json.Formatting.Indented);
                    this.ResponseWrite(json);
                    return;
                case "AppDemo_KaiPiaoList_Init": //获得开票列表.
                    sql = "SELECT * FROM DevelopCCBPMServicesDemo.dbo.ND3Rpt ";
                    dt = this.RunSQLReturnDataTable(sql);
                    json = Newtonsoft.Json.JsonConvert.SerializeObject(dt, Newtonsoft.Json.Formatting.Indented);
                    this.ResponseWrite(json);
                    return;
                case "AppDemo_CuiKuanList_Init": //催款列表.
                    sql = "SELECT * FROM DevelopCCBPMServicesDemo.dbo.ND4Rpt ";
                    dt = this.RunSQLReturnDataTable(sql);
                    json = Newtonsoft.Json.JsonConvert.SerializeObject(dt, Newtonsoft.Json.Formatting.Indented);
                    this.ResponseWrite(json);
                    return;
                default:
                    break;
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write("err@没有处理的标记:" + doType);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public void Portal_Login_Submit()
        {
            //获得传来的变量.
            string no = context.Request.QueryString["No"];
            string pass = context.Request.QueryString["Pass"];

            //判断用户是否存在?
            DataTable dt = this.RunSQLReturnDataTable("SELECT * FROM ERP_User WHERE BH='" + no + "'");
            if (dt.Rows.Count == 0)
            {
                ResponseWrite("err@用户名密码错误.");
                return;
            }

            //这里校验密码.
            string password = dt.Rows[0]["Password"].ToString();
            //if (1 == 2)
            //{
            //    ResponseWrite("err@用户名密码错误.");
            //    return;
            //}

            //生成一个GUID. 
            string sid = System.Guid.NewGuid().ToString();
            //更新到人员表里，如果您是集成模式，就需要更新您自己的用户表.
            //这一点非常重要，因为需要sid就是token，要访问ccbpm的服务需要用到它做身份认证.
            string sql = "UPDATE ERP_User SET SID='" + sid + "' WHERE BH='" + no + "'";
            this.RunSQL(sql);
            ResponseWrite(sid);
        }

        #region 通用方法.
        public void ResponseWrite(string strs)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write(strs);
        }
        /// <summary>
        /// 运行SQL获得影响的行数.
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int RunSQL(string sql)
        {
            SqlConnection conn = new SqlConnection(dsn);
            SqlCommand cmd = null;
            try
            {
                if (conn == null)
                    conn = new SqlConnection(dsn);

                if (conn.State != System.Data.ConnectionState.Open)
                {
                    conn.ConnectionString = dsn;
                    conn.Open();
                }
                cmd = new SqlCommand(sql, conn);
                cmd.CommandType = CommandType.Text;

                return cmd.ExecuteNonQuery();
            }
            catch (System.Exception ex)
            {
                throw new Exception("RunSQL2 step=" + ex.Message + " 设置连接时间=" + conn.ConnectionTimeout);
            }
            finally
            {
                if (cmd != null)
                    cmd.Dispose();
                if (conn != null)
                    conn.Dispose();
            }
        }
        /// <summary>
        /// 运行SQL获得Data
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable RunSQLReturnDataTable(string sql)
        {
            SqlConnection conn = new SqlConnection(dsn);
            try
            {
                if (conn == null)
                {
                    conn = new SqlConnection(dsn);
                    conn.Open();
                }

                if (conn.State != ConnectionState.Open)
                {
                    conn.ConnectionString = dsn;
                    conn.Open();
                }

                SqlDataAdapter oraAda = new SqlDataAdapter(sql, conn);
                oraAda.SelectCommand.CommandType = CommandType.Text;

                DataTable oratb = new DataTable("otb");
                oraAda.Fill(oratb);

                // peng add 07-19
                oraAda.Dispose();
                return oratb;
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.Message + " [RunSQLReturnTable dsn=App ] sql=" + sql + "<br>");
            }
            finally
            {
                if (conn != null)
                    conn.Dispose();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion 通用方法.

    }
}